import { observable, action, autorun, toJS } from "mobx";
import { message, Modal } from "antd";
import _ from 'lodash';
import $ from "jquery";
import { CommonStore } from "../../commonStore";
import TabsStore from "../../util/tabs";
import { tabs } from "../../data/board";
import { WeaTableNew, WeaForm } from 'comsMobx'
const { TableStore } = WeaTableNew;
import * as  Apis from '../../../apis/projecboard';
import * as  PrjApis from '../../../apis/project';
import { PrjCardStore } from "../../projectBoard/prjCardStore";
import { TaskCardStore } from "../../projectBoard/taskCardStore";
import {WeaLocaleProvider} from "ecCom"
const getLabel = WeaLocaleProvider.getLabel;
export class PrjBoardStore {

    @observable loading = false;
    @observable title = '';
    @observable prjList = [];


    //项目类型树
    @observable treeDatas = [];
    @observable treeCount = {};
    @observable treeCountType = [];
    @observable selectedTreeKey = "";


    @observable rightMenus = [];
    @observable currentKey = "1";
    @observable pagination = {
        pageSize: 10,
        current: 1,
        total: 0
    }
    @observable prjListloading = true;
    @observable searchType = "stageid";
    @observable searchTypeOptions = [];
    @observable canEditBoard = true;
    @observable canEditBoardTask = true;
    @observable canAddTask = true;
    @observable showLandMark = true;
    @observable isedit = true;
    @observable commonStore = new CommonStore();
    @observable tabsStore = new TabsStore();
    @observable prjid = "";
    @observable targetid = "";
    @observable taskid = "";
    @observable treeid = "";
    @observable tableStore = new TableStore();
    @observable columns = [];
    @observable prjValue = "";
    @observable prjCardStore = new PrjCardStore();
    @observable prjTaskCardStore = new TaskCardStore();
    @observable SlideModalVisible = false;
    @observable refelsh = 0;
    @observable userid = "";
    @observable username = "";
    @observable usericons = "";
    discusstype = "PP";
    //相关交流
    @observable exchangeform = new WeaForm();
    @observable exchangeRightMenu = [];
    @observable exchangeContent = {}  //相关交流内容
    @observable showSearchAd = false  // 高级搜索显示
    @observable condition = []; //高级搜索
    @observable showLeft = false;
    @observable showMid = true;

    @observable isNow = true; //任务是否是历史版本

    columnGrids_map = [];
    columnGrids = [];
    boardGrid;
     /**
     * column拖拽信息start,拖拽结束后与结束时信息对边判断移动的位置
     */
    column_move_info;
    /**
     * item拖动前所在的grid
     */
    item_move_old_grid;
    item_move_info;
    item_move_start_index;

    @observable windowHeight=window.innerHeight;
    @observable windowWidth=window.innerWidth;
    @observable timestamp = new Date().getTime()+'';
    @observable percentStaus =  new Date().getTime()+'';
    @observable boardform = new WeaForm();
    /**
     * 初始化看板拖动元素document.querySelector('.prj_board_container')
     */
    @action
    initBoard = () => {
        var borderContainer = document.querySelector('.prj_board_container');
        var board = borderContainer.querySelector('.board');
        var itemContainers = Array.prototype.slice.call(borderContainer.querySelectorAll('.board-column-content'));
        itemContainers.forEach(container=>this.initItem(container));
        const _this = this;
        this.loading = true;
        this.boardGrid = new Muuri(board, {
            layout: function (items, gridWidth, gridHeight) {
                // The layout data object. Muuri will read this data and position the items
                // based on it.
                var layout = {
                  // The layout item slots (left/top coordinates).
                  slots: [],
                  // The layout's total width.
                  width: 0,
                  // The layout's total height.
                  height: 450,
                  // Should Muuri set the grid's width after layout?
                  setWidth: true,
                  // Should Muuri set the grid's height after layout?
                  setHeight: false
                };
                // Calculate the slots.
                var item;
                var m;
                var x = 0;
                var y = 0;
                var w = 0;
                // var h = 0;
                for (var i = 0; i < items.length; i++) {
                  item = items[i];
                  x += w;
                  //y += h;
                //   console.log(item.getMargin(),item.getWidth());
                  m = item.getMargin();
                  w = item.getWidth() + m.left;
                //   h = item.getHeight() + m.top + m.bottom;
                  layout.slots.push(x, y);
                }
                // Calculate the layout's total width and height. 
                // console.log(x + w);
                layout.width = x + w;
                // layout.height = h;
                return layout;
            },
            layoutDuration: 400,
            layoutOnResize:true,
            layoutEasing: 'ease',
            dragEnabled: true,
            dragSortInterval: 0,
            dragStartPredicate:function (item, event) {


                if (!_this.canEditBoard || _this.boardGrid.getItems().indexOf(item) === _this.boardGrid.getItems().length-1) {
                    return false;
                  }
    
                // For other items use the default drag start predicate.
                return Muuri.ItemDrag.defaultStartPredicate(item, event,{
                    handle: '.board-column-header'
                });
            },
            dragSortPredicate: function (item) {
                // console.log(item);
              var result = Muuri.ItemDrag.defaultSortPredicate(item, {
                action: 'swap',
                threshold: 50
              });
            //   console.log(result,result.index === _this.boardGrid.getItems().length-1||result.index === _this.boardGrid.getItems().length-2);
              return result  && (_this.canEditBoard &&  result.index === _this.boardGrid.getItems().length-1) ? false : result;;
            },
            dragReleaseDuration: 400,
            dragReleaseEasing: 'ease'
        }).on('move', function (data) {
            // console.log(data);
            _this.column_move_info.push(data);
            // console.log( _this.column_move_info);
        }).on('dragMove', function (item, event) {
            // console.log(item, event);
            if(event){
                let borderDiv=$('#prj_board_container');
                if((event.center.x+item.getWidth()/2)>window.innerWidth){
                    borderDiv.scrollLeft(borderDiv.scrollLeft()+20);
                }
                if(event.center.x-item.getWidth()/2<0){
                    borderDiv.scrollLeft(borderDiv.scrollLeft()-20);
                }
            }
        }).on('dragStart', function (item) {
            _this.column_move_info=[];
        }).on('dragReleaseEnd', function (item) {
            // console.log(_this.column_move_info.length,item);
            if(_this.column_move_info.length!=0){
                let startD=_this.column_move_info[0];
                let endD=_this.column_move_info[_this.column_move_info.length-1];
                if(startD.fromIndex!=endD.toIndex){
                    let leftgroupid=endD.toIndex==0?"":_this.boardGrid.getItems()[endD.toIndex-1]._element.getAttribute('id').replace('column_','')
                    Apis.saveGroupOrder({ prjid:_this.prjid,stageid:item._element.getAttribute('id').replace('column_',''),leftstageid:leftgroupid}).then(({ success }) => {
                        if (success) {
                            message.success(getLabel(389171, "排序保存成功！"));
                        } else {
                            message.error(getLabel('503631','排序保存失败！') );
                        }
                    });
                }
            }
        })
        this.loading = false;
    }

    /**
     * 初始化item元素
     */
    initItem=(container,isSearch=false)=>{
        const Muuri = window['Muuri'];
        const _this = this;
        var muuri = new Muuri(container, {
            items: '.board-item',
            layoutDuration: 400,
            layoutEasing: 'ease',
            dragEnabled: true,
            dragSortInterval: 0,
            dragSort: function () {
                return _this.columnGrids;
            },
            dragStartPredicate:function (item, event) {

               
                // console.log('dragStartPredicate',event);
                if(event.target.parentNode&&event.target.parentNode.className){
                    if(event.target.parentNode.className=='item-icon'||event.target.parentNode.className=='landmark'||event.target.parentNode.className=='detail'||event.target.className=='title'){
                        return;
                    }
                }
               
                if(event&&event.target&&(event.target.className=='manager-img'||event.target.className=='icon-coms-Flag')){
                    return;
                }
                
                if (!_this.canEditBoardTask) {
                    return false;
                  }

                return Muuri.ItemDrag.defaultStartPredicate(item, event,{
                    handle: '.board-item'
                });
            },
            dragContainer: document.querySelector('.prj_board_container'),
            dragReleaseDuration: 400,
            dragReleaseEasing: 'ease'
        })
        .on('move', function (data) {
            _this.item_move_info.push(data);
        }).on('receive', function (data) {
            _this.changeStatus();
        })
        .on('dragStart', function (item,event) {
            // console.log("dragStart",item,event);
            // console.log(item.getElement().style.transform);
            // item.getElement().style.transform = "rotate(5deg)";
            item.getElement().style.width = item.getWidth() + 'px';
            item.getElement().style.height = item.getHeight() + 'px';
            _this.item_move_old_grid=item.getGrid();
            _this.item_move_info=[];
            _this.item_move_start_index=item.getGrid().getItems().indexOf(item);
        })
        .on('dragReleaseEnd', function (item) {
            // console.log("dragReleaseEnd",item,item.getGrid()._element);
            item.getElement().style.width = '';
            item.getElement().style.height = '';
            _this.columnGrids.forEach(function (grid) {
                grid.refreshItems();
            });
            if(item.getGrid()!=_this.item_move_old_grid){//移出到另一个column中
                let currentId=item._element.getAttribute('id');
                let i=item.getGrid().getItems().indexOf(item);
                let previousId=item.getGrid().getItems()[i-1]?item.getGrid().getItems()[i-1]._element.getAttribute('id'):'';
                let nextId=item.getGrid().getItems()[i+1]?item.getGrid().getItems()[i+1]._element.getAttribute('id'):'';
                _this.saveItemOrder(true,currentId,item.getGrid()._element.getAttribute('id'),previousId,nextId);
                // console.log(true,currentId,item.getGrid()._element.getAttribute('id'),previousId,nextId);
            
            }else if(_this.item_move_info.length!=0){//自己column中移动
                let startD=_this.item_move_info[0];
                let endD=_this.item_move_info[_this.item_move_info.length-1];
                if(startD.fromIndex!=endD.toIndex&&_this.item_move_start_index!=endD.toIndex){
                    let currentId=item._element.getAttribute('id');
                    let i=item.getGrid().getItems().indexOf(item);
                    let previousId=item.getGrid().getItems()[i-1]?item.getGrid().getItems()[i-1]._element.getAttribute('id'):'';
                    let nextId=item.getGrid().getItems()[i+1]?item.getGrid().getItems()[i+1]._element.getAttribute('id'):'';
                    _this.saveItemOrder(false,currentId,item.getGrid()._element.getAttribute('id'),previousId,nextId);
                    // console.log(false,currentId,item.getGrid()._element.getAttribute('id'),previousId,nextId);
                }
            }
      
        })
        .on('layoutStart', function () {
            _this.boardGrid.refreshItems().layout();
        })
        .on('dragMove', function (item, event) {
            // item.getElement().style.transform = item.getElement().style.transform+" rotate(-5deg)";
            if(event){
                //上下拖动
                let pElement=$(item.getGrid()._element.parentNode);
                if(event.center.y+item.getHeight()/2>item.getGrid()._top+pElement.scrollTop()+$(pElement).height()){
                    pElement.scrollTop(pElement.scrollTop()+20);
                }
                if(event.center.y-item.getHeight()/2<item.getGrid()._top+pElement.scrollTop()){
                    pElement.scrollTop(pElement.scrollTop()-20);
                }
                //左右拖动
                let borderDiv=$('#prj_board_container');
                if((event.center.x+item.getWidth()/2)>window.innerWidth){
                    borderDiv.scrollLeft(borderDiv.scrollLeft()+20);
                }
                if(event.center.x-item.getWidth()/2<0){
                    borderDiv.scrollLeft(borderDiv.scrollLeft()-20);
                }
            }
        });
        _this.columnGrids.push(muuri);
        _this.columnGrids_map[container.getAttribute('id')]=muuri;
    }

    /**
     * 计数状态修改
     */
    @action
    changeStatus=(data)=>{
       this.percentStaus = new Date().getTime()+'';
    }

      /**
     * 保存任务元素排序,优先排在上一个的下边，或排在下一个的上边，或排在第一个
     */
    saveItemOrder=(isChangeGroup,itemid,groupid,previousId,nextId)=>{
        itemid=itemid.replace('item_','');
        previousId=previousId.replace('item_','');
        nextId=nextId.replace('item_','');
        groupid=groupid.replace('column_content_','');
        const _this = this;
        // this.loading = true;
        Apis.saveItemOrder({isChangeGroup:isChangeGroup,taskId:itemid,groupId:groupid,previousId:previousId,nextId:nextId,viewType:_this.searchType,prjid:_this.prjid}).then(({success})=>{
            if(success){
                message.success(getLabel(389171, "排序保存成功！"));
                _this.changeStatus();
            }else{
                message.error("保存失败");
            }   
            // _this.loading = false;
        });

    }





    constructor() {
        this.columns = [
        ];
        this.tabsStore.tabs = tabs;
        this.tabsStore.activeKey = localStorage.getItem("prj_board_activeKey") || '1';
        this.prjCardStore.selectTabKey = localStorage.getItem("prj_board_activeKey") || '1';
        this.tabsStore.onChange = action((key) => {
            this.tabsStore.activeKey = key;
            this.prjCardStore.selectTabKey = key;
            this.initRightPage();
        });
        autorun(() => {
            if (this.prjid) {
                localStorage.setItem("prj_board_selectedKey", this.prjid);
            }
            if (this.tabsStore.activeKey) {
                localStorage.setItem("prj_board_activeKey", this.tabsStore.activeKey);
            }
        });
    }

    @action
    onCollapse = (side,bool) =>{
        if(side == "left"){
            this.showLeft = bool;
        }else{
            this.showMid = bool;
        }
    }

    //高级搜索显隐
    setShowSearchAd=(bool)=>{
        this.showSearchAd = bool
    }

    @action
    onChangePaginNation = (current = this.pagination.current, pageSize = this.pagination.pageSize) => {
        this.pagination.current = current;
        this.pagination.pageSize = pageSize;
        this.getCurrentPageDatas();
    }

    @action
    initList = (prjid) => {
        if(prjid!== ""){
            this.prjid = prjid;
        }
    }

    @action
    setPrjTypeId = (params) => {
        localStorage.setItem("prj_treeid", params.prjtype);
        this.pagination.current = 1;
        this.getCurrentPageDatas();
    }

    @action 
    saveTaskInfo = (params) => {
        if(this.prjCardStore.saveTaskInfo(this)){
            this.searchKanBanView(false);
        }
    }

    @action
    getTreeList = (params) => {
        Apis.getPrjTypeTreePageList({ treetype: 'prjsearch', ...params }).then(data => {
            this.treeDatas = data.treedata;
            this.treeCount = data.treecount;
            this.treeCountType = data.treecountcfg;
            this.setSelectedTreeKey("prjtype_" + data.selectedKeys);
            localStorage.setItem("prj_treeid", data.selectedKeys);
            this.getProjectList();           
        })
    }

    @action 
    setLandMark=(id,value)=>{
        Apis.setLandMark({ taskid : id, value : value }).then(data => {
            if(data.success){
                this.searchKanBanView(false);
            }else{
                message.success("设置失败，请联系系统管理员！");
            }
        })
    }

    @action
    saveTask = (params) => {
        Apis.addBoardTask({ ...params, prjid: this.prjid }).then(data => {
            this.searchKanBanView(false);
        });
    }

    @action 
    delGrop = (id) => {
        const _this = this;
        Modal.confirm({
            title:getLabel(15172,"系统提示"),
            content:getLabel('503589','该阶段下的任务以及子任务都会被删除，您确定要删除吗？') ,
            onOk() {
                Apis.delBoardStage({stageid:id}).then(data => {
                    _this.searchKanBanView(true);
                });
            },
            onCancel() { },
            okText : getLabel('33703','确认') ,
            cancelText : getLabel('31129','取消') 
        });
        
    }

    @action
    saveGroup = (name) => {
        Apis.addBoardStage({title:name, prjid: this.prjid }).then(data => {
            this.searchKanBanView(false);
        });
    }

    @action
    saveGroupName = (name,id) =>{
        Apis.editBoardStage({title:name, stageid:id}).then(data => {
            this.searchKanBanView(false);
        });
    }

    @action
    getProjectList = (params={pageIndex : this.pagination.current, pageSize : this.pagination.pageSize}) => {
        this.treeid = localStorage.getItem("prj_treeid");
        this.prjListloading = true;
        let list = [];
        if(this.treeid == "" || this.treeid == null){
            this.treeid = -1
        }
        Apis.getPrjByTypeId({ ...params, prjtype: this.treeid }).then(data => {
            list = data.datas;
            list = list.map((item) => {
                let { name, person, money, id, state, color } = item;
                return { name, person, money, id, state, color, key: id, };
            });
            this.prjList = list;
            this.pagination.total = data.totalSize;
            this.setPrjid();
            this.prjListloading = false;
        });
    }

    @action
    setPrjid = (prjid = localStorage.getItem("prj_board_selectedKey") || this.prjid) => {
        let filter = this.prjList.slice().filter(d => d.key == prjid);
        if (prjid && filter.length > 0) {
            this.prjid = prjid;
        } else {
            this.prjid = _.get(this.prjList.slice(), '[0].key');
            filter = this.prjList.slice(0, 1);
        }
        this.prjCardStore.setPrjId(this.prjid);
        this.title = `${_.get(filter, '[0].name') || ""} `;
        this.currentKey = this.prjid;
        //this.prjCardStore.getPrjInfoForBoard({ prjid: this.prjid });
        this.getPrjTabs();
    }

    @action
    getKanbanView = () => {
        const searchParams = this.boardform.getFormParams();
        Apis.getKanbanView({prjid:this.prjid,...searchParams,searchType:this.searchType}).then(data=>{
            this.columns = data.stages;
            this.userid = data.userid;
            this.usericons = data.useridicon;
            this.username = data.useridname;
            this.isedit = data.isedit;
            this.canAddTask = data.cantask;
            this.canEditBoard = data.canboard;
            this.canEditBoardTask = data.canboardtask;
            this.condition = data.condition;
            this.boardform && !this.boardform.isFormInit && this.boardform.initFormFields(data.condition);
            this.searchTypeOptions = data.searchTypeOptions;
            this.showLandMark = data.showLandMark;
            // this.timestamp=new Date().getTime()+'';
            this.initBoard();
            this.changeStatus();
        });
    }

    searchKanBanView = ( needRefelshView = false) => {
        if(needRefelshView){
            this.columns = [];
        }
        // const searchParams = this.boardform.getFormParams();
        this.refelsh++;
        if(needRefelshView){
            this.timestamp=new Date().getTime()+'';
            this.initBoard();
        }
        // Apis.getKanbanView({prjid:this.prjid,...searchParams,searchType:this.searchType}).then(data=>{
          
        //     this.columns = data.stages;
        //     this.userid = data.userid;
        //     this.usericons = data.useridicon;
        //     this.username = data.useridname;
        //     this.isedit = data.isedit;
        //     this.canAddTask = data.cantask;
        //     this.canEditBoard = data.canboard;
        //     this.changeStatus();
        //     if(needRefelshView){
        //         this.timestamp=new Date().getTime()+'';
        //         this.initBoard();
        //     }
        // });
    }

    @action
    getPrjTabs=(params={})=>{
		this.loading = true;
        Apis.getPrjTabs({prjid:this.prjid}).then(data=>{
			if(!data.isright && typeof(data.isright) !== "undefined"){
				this.tabsStore.hasRight = data.isright;
				this.tabsStore.verified = true;
			}else{
				this.tabsStore.hasRight = true;
				this.tabsStore.verified = true;
                this.tabsStore.tabDatas = data.tabs ;
                this.initRightPage();
				this.loading = false;
			}
        })
        
	}

    initRightPage = () => {
        if (!this.prjid) {
            return;
        }
        const tabDatas1 = toJS(this.tabsStore.tabDatas);
        if (tabDatas1) {
            this.prjCardStore.clearStatus();
            for (let i = 0; i < tabDatas1.length; i++) {
                if(this.tabsStore.activeKey == tabDatas1[i].key){
                    switch (tabDatas1[i].shortname) {
                        case 'taskboard':
                            
                            break;
                        case 'prjinfo':
                            this.prjCardStore.getPrjInfo({viewtype:'view',prjid:this.prjid});
                            this.rightMenus = this.prjCardStore.rightMenu;
                            if (!window.weaWorkplan) {
                                // 异步加载别模块的静态资源
                                eventRegister.loadModule('f_workplan', () => {
                                    this.prjCardStore.setLoaded(true)
                                }, () => {
                                    // 加载文件失败 的业务处理， 网络超时，没文件之类
                                })
                            } else {
                                this.prjCardStore.setLoaded(true)
                            }
                            break;
                        case 'childprj':
                            this.prjCardStore.getPrjSubList({prjid:this.prjid});
                            this.prjCardStore.getPrjSubCondition();
                            break;
                        case 'tasklist':
                            this.prjCardStore.getPrjTaskList({prjid:this.prjid});
                            this.prjCardStore.getPrjTaskCondition({prjid:this.prjid});
                            this.prjCardStore.getPrjTaskVersion({prjid:this.prjid});
                            break;
                        case 'prjdiscuss':
                            this.targetid = this.prjid;
                            this.prjCardStore.getExchangeList({});
                            break;
                        case 'prjshare':
                            this.prjCardStore.getPrjShareList({prjid:this.prjid});
                            break;
                        case 'stareport':
                            this.prjCardStore.getPrjStastics({prjid:this.prjid});
                            this.rightMenu = [];
                            break;
                        case 'stageset':
                            this.prjCardStore.clearStageStatus();
                            this.prjCardStore.getPrjTempletStageList({prjid:this.prjid});
                            this.rightMenu = [];
                            break;
                        case 'resources':
                            this.prjCardStore.getPrjResourceInfo({prjid:this.prjid});
                            this.rightMenu = [];
                    }
                }
                
            }
        }
        
    }

    //相关交流
	getRelateExchangeInfo = (params={})=>{
		this.loading = true;
		const searchParamsAd = this.exchangeform.getFormParams();
		const newParams = { types:"PP",sortid:this.prjid, ...searchParamsAd, ...params };
		for(let item in newParams){
            if(newParams[item] == ""){
                delete newParams[item]
            }
         };
        PrjApis.getPrjDiscuss(newParams).then(data=>{
			this.exchangeRightMenu = data.rightMenus;
			this.exchangeContent = data;
			this.loading = false;
		})
	}

    @action
    getCurrentPageDatas = (current = this.pagination.current, pageSize = this.pagination.pageSize) => {
        this.getProjectList({
            pageIndex: current,
            pageSize: pageSize,
            prjname: this.prjValue
        });
    }

    @action
    changeSelectedKey = (key) => {
        this.setPrjid(key)
    }

    @action
    onSearchChange = (value) =>{
        this.prjValue = value;
    }

    @action
    onSearchListItem = (value) => {
        this.prjValue = value;
        this.pagination.current = 1;
        this.getCurrentPageDatas();
        // this.pagination.total = list.length;
    }

    @action
    getRightMenuForTop = () => {

    }

    @action
    showSlideModal = (bool, v) => {
        this.SlideModalVisible = bool;
        this.taskid  =  typeof (v) == "object" ? v.id : v;
    }

    setSelectedTreeKey = (key) => {
        if(  this.selectedTreeKey !== key){
            this.selectedTreeKey = key;
        }
        this.prjValue = "";
    }

    @action 
    clearStatus = () =>{
        this.columns = [];
    }

    //form 重置
    clearFormFields=()=>{
        if(this.tabsStore.activeKey == "3"){
            this.exchangeform.reset();   //清除查询条件值
        }
        // if(this.tabsStore.activeKey == "0"){
            this.boardform.reset();   //清除查询条件值
		// }

    }
    
    //高级搜索设值
    setFormFields=(value)=>{
		if(this.tabsStore.activeKey == "3"){  //相关交流
            this.exchangeform.updateFields(value, false);    //true代表完全覆盖方式更新条件值
		}
    }
    
    changeSearchType = (searchType) => {
        this.searchType = searchType;
        this.searchKanBanView(false);
    }

    setIsNow=(v)=>{
		this.isNow = v;
    }

  
}

export default new PrjBoardStore